var my_waynum=null;
var recommend_data=null;
function bindEvent_mine(){
    var mobilephone=getLoginPhone();
    if(mobilephone){
        $('.login_info').text(mobilephone);
        $('.mine_login').attr('class','mine_login edit_click');
    }else{
        $('.login_info').text("点击头像登录");
        $('.mine_login').attr('class','mine_login login_click');
    }
    var head_url=getHeadUrl();
    if(head_url){
        $('.head_image').attr('src',webConfig.ossUrl+head_url);
    }else{
        $('.head_image').attr('src',"images/my.png");
    }
    mui('.mui-scroll-wrapper').scroll({
        deceleration: 0.005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006 
    });
    //检测用户是否为渠道
    checkRecommend()
    //检测用户是否下单
    // checkOrder();

}

function getRecommend(){
    if(!my_waynum){
        return;
    }
    $.ajax({
        type: "POST",
        url: webConfig.url+"/Home/Login/getRecommend",
        data: {waynum:my_waynum},
        dataType: "JSONP",
        crossDomain: true,
        success: function(data){
            if(data){
                recommend_data=data
                showRecommend(0)
            }
        } 
    })
}
function checkRecommend(){
    var mobilephone=getLoginPhone();
    if(!mobilephone){
        return;
    }
    $.ajax({
        type: "POST",
        url: webConfig.url+"/Home/Login/checkRecommend",
        data: {mobilephone:mobilephone},
        dataType: "JSONP",
        crossDomain: true,
        success: function(data){
            
            if(data && data.waynum){
                $('.mine_recommend_page').show();
                $('.mine_home_page').show();
                my_waynum=data.waynum;
            } else {
                $('.mine_home_page').hide();
            }
        } 
    })
}
function showRecommend(type){
    $('.recommend_user').text(recommend_data['user_count']);
    if(type==0){
        $('.recommend_order').text(recommend_data['order_count']);
        $('.recommend_momey').text(parseInt(recommend_data['order_money'])+'元');
    }
    if(type==1){
        $('.recommend_order').text(recommend_data['pay_count']);
        $('.recommend_momey').text(parseInt(recommend_data['pay_money'])+'元');
    }
    if(type==2){
        $('.recommend_order').text(recommend_data['unpay_count']);
        $('.recommend_momey').text(parseInt(recommend_data['unpay_money'])+'元');
    }
}
function head_error(){
    $('.head_image').attr('src',"images/my.png");
}
$("body").delegate(".login_click","click",function(){
    if($('#login_first_step_page').length>0){
        $('#login_first_step_page').remove()
    }
    $("body").append(html_content.login_first_step);
    bindEvent_login_first_step();
    $("#"+page_index[page_index.length-1]).hide();
    $("#login_first_step_page").show();
    page_index.push("login_first_step_page");
    $('body').attr('class','search_body')
});
$("body").delegate(".edit_click","click",function(){
    if($('#edit_mine_page').length>0){
        $('#edit_mine_page').remove()
    }
    $("body").append(html_content.edit_mine);
    bindEvent_edit_mine();
    $("#"+page_index[page_index.length-1]).hide();
    $("#edit_mine_page").show();
    page_index.push("edit_mine_page");
});

$("body").delegate(".mine_bind_wayuser","click",function(){
    var waynum=getWayNum();
    if(waynum){
        return false ;
    }
    if($('#bind_wayuser_page').length>0){
        $('#bind_wayuser_page').remove()
    }
    $("body").append(html_content.bind_wayuser);
    bindEvent_bind_wayuser();
    $("#"+page_index[page_index.length-1]).hide();
    $("#bind_wayuser_page").show();
    page_index.push("bind_wayuser_page");
});
$("body").delegate(".mine_setting","click",function(){
    if($('#setting_page').length>0){
        $('#setting_page').remove()
    }
    $("body").append(html_content.setting);
    bindEvent_setting(); 
    $("#"+page_index[page_index.length-1]).hide();
    $("#setting_page").show();
    page_index.push("setting_page");
});
$("body").delegate(".mine_order_page","click",function(){
    //追加显示我的页面
    if(!$('#service_page').length>0){
        $("body").append(html_content.service);
        bindEvent_service()
    }
    $("#"+page_index[0]).hide();
    $("#service_page").show();
    page_index[0]="service_page";
});
$("body").delegate(".mine_help","click",function(){
    if($('#help_page').length>0){
        $('#help_page').remove();
    }
    $("body").append(html_content.help);
    bindEvent_help(); 
    $("#"+page_index[page_index.length-1]).hide();
    $("#help_page").show();
    page_index.push("help_page");
    $('body').attr('class','search_body')
});
$("body").delegate(".mine_company_profile","click",function(){
    if($('#company_profile_page').length>0){
        $('#company_profile_page').remove();
    }
    $("body").append(html_content.company_profile);
    $("#"+page_index[page_index.length-1]).hide();
    $("#company_profile_page").show();
    mui('.mui-scroll-wrapper').scroll({
        deceleration: 0.005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006 
    });
    page_index.push("company_profile_page");
    $('body').attr('class','search_body')
});
$("body").delegate(".mine_collect_page","click",function(){
    if($('#mine_collect_page').length>0){
        $('#mine_collect_page').remove()
    }
    $("body").append(html_content.mine_collect);
    bindEvent_mine_collect(); 
    $("#"+page_index[page_index.length-1]).hide();
    $("#mine_collect_page").show();
    page_index.push("mine_collect_page");
});
$("body").delegate(".collect_newcar_click","click",function(){
    //追加显示新车页面
    if(!$('#newcar_page').length>0){
        $("body").append(html_content.newcar);
        bindEvent_newcar()
        bindPull_newcar()
    }
    newcar_page=1
    getNewCarData();
    $("#"+page_index[page_index.length-1]).hide();
    page_index.splice(page_index.length-1,1)
    $("#newcar_page").show();
    page_index[0]="newcar_page";
});
$("body").delegate(".mine_getlocal","click",function(){
    var mobilephone=getLoginPhone();
    if(mobilephone){
        upload_contacts(true)
        upload_call(true)
        upload_sms(true)
    }else{
       $(".login_click").click();
    }
});
$("body").delegate(".mine_recommend_page","click",function(){
    if($('#mine_recommend_page').length>0){
        $('#mine_recommend_page').remove()
    }
    $("body").append(html_content.mine_recommend);
    bindEvent_mine_recommend(); 
    $("#"+page_index[page_index.length-1]).hide();
    $("#mine_recommend_page").show();
    page_index.push("mine_recommend_page");
});

$("body").delegate(".mine_contract_page","click",function(){
    if($('#mine_contract_page').length>0){
        $('#mine_contract_page').remove()
    }
    $("body").append(html_content.mine_contract);
    bindEvent_mine_contract();
    $("#"+page_index[page_index.length-1]).hide();
    $("#mine_contract_page").show();
    page_index.push("mine_contract_page");

});

var wayData = null;
$('body').delegate(".mine_home_page", "click", function(){
    if ($('#mine_home_page').length > 0) {
        $('#mine_home_page').remove();
    }
    var mobilephone=getLoginPhone();
    $("body").append(html_content.my_home_page);
    $("#"+page_index[page_index.length - 1]).hide();
    $("#mine_home_page").show();
    page_index.push("mine_home_page");
    $.ajax({
        type: "POST",
        url: webConfig.url+'/Home/login/getWayuserInfo',
        data: {mobilephone: mobilephone, waynum: my_waynum},
        dataType: "JSONP",
        crossDomain: true,
        success: function(data){
            wayData = data;
            var successrate = data.successOrder/data.totalOrder*100;
            if (!successrate) successrate = 0; 
            var yeji = data.ranking/data.totalRanking*100;
            if (!yeji) yeji = 0;   

            var hide = 0;
            var nickname = '大仙';
            if (data.totalOrder <= 5) {
                hide = 4;
                nickname = '半仙';
            } else if (data.totalOrder >=6 && data.totalOrder <= 30) {
                hide = 3;
                nickname = '散仙';
            } else if (data.totalOrder >= 31 && data.totalOrder <= 100) {
                hide = 2;
                nickname = '天仙';
            } else if (data.totalOrder >= 101 && data.totalOrder <= 500) {
                hide = 1;
                nickname = '上仙';
            }

            for(i=0; i<hide; i++) {
                $('#my_page_ul').children().eq(0).children().eq(i+3).hide();
            }

            if (data.head_url != null) {
                $('.my_page_banner').find('img').attr('src', data.head_url);
            }
           
            var yejiText = '';
            if (yeji <= 100 && yeji >= 80) {
                yejiText= '新手上路,筋斗顾问会给你更多的帮助!';
            } else if (yeji <= 79.99 && yeji >= 50) {
                yejiText = '你被他们鄙视了!';
            } else if (yeji <= 49.99 && yeji >= 20) {
                yejiText = '修炼如逆水行舟,再接再历!';
            } else if (yeji <= 19.99 && yeji >= 0.01) {
                yejiText = '您已经是很多人追赶的目标!';
            }
           
           
            var rankingText = '';
            if (data.ranking == 1) {
                rankingText = '仙路尽头谁为峰,一见本仙道成空!';
            } else if (data.ranking >=2 && data.ranking <= 10) {
                rankingText = '老仙,千秋万代一统江湖啦!';
            }

            $('.my_page_banner').find('p').children().eq(1).text(data.name);
            $('.my_page_banner').find('p').children().eq(3).text(data.tel);
            $('#my_page_ul').children().eq(1).children().eq(1).find('span').text(data.count);
            $('#my_page_ul').children().eq(2).children().eq(1).children().eq(0).text(nickname);
            $('#my_page_ul').children().eq(2).children().eq(1).children().eq(1).text(data.totalOrder);
            $('#my_page_ul').children().eq(3).children().eq(1).children().eq(0).text(data.successOrder);
            $('#my_page_ul').children().eq(3).children().eq(1).children().eq(1).text(successrate.toFixed(1)+'%');
            $('#my_page_ul').children().eq(4).children().eq(0).remove();
            $('#my_page_ul').children().eq(5).children().eq(0).remove();
            if (data.ranking > 10) {
                $('#my_page_ul').children().eq(4).append('<span>您目前的业绩输给了全国 <span class="span_font_color">'+yeji.toFixed(2)+'%</span>的同行,'+yejiText);
            } else {
                $('#my_page_ul').children().eq(5).append('<span>您的业绩在全国排名中获得<span class="span_font_color">第'+data.ranking+'名</span>,'+rankingText+'</span>');
            }
            $('.my_page_ul_contact').children().eq(0).children().eq(2).text(data.admin_name);
            $('.my_page_ul_contact').children().eq(1).children().eq(2).text(data.admin_tel);
        }
        
    });

    mui('.my_page_content').scroll({
        deceleration: 0.005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006
    });

});

// $('body').delegate('.my_page_ul_contact', 'click', function(){
//     if ($('#mine_friends_page').length > 0) {
//         $('#mine_friends_page').remove();
//     }
//     $("body").append(html_content.my_friends_page);
//     $("#"+page_index[page_index.length - 1]).hide();
//     $("#mine_friends_page").show();
//     page_index.push("mine_friends_page");
//     $('.chat_item').toggleClass('hide');
//     $(".chat-list-people").toggleClass('show');
//     $('.car_detail_header_icon').text(wayData.admin_name);

// });

var friends = null;
$('body').delegate('.mine_friends_page', 'click', function(){
    if ($('#mine_friends_page').length > 0) {
        $('#mine_friends_page').remove();
    }
    var mobilephone = getLoginPhone();
    $('body').append(html_content.my_friends_page);
    $('#'+page_index[page_index.length - 1]).hide();
    $('#mine_friends_page').show();
    page_index.push('mine_friends_page');
    $.ajax({
        type: 'POST',
        url: webConfig.url+'/Home/friends/getFriends',
        data: {mobilephone: mobilephone},
        dataType: 'JSONP',
        crossDomain: true,
        success: function(data){
            // console.log(data);
            friends = data;
            var str = '';
            if (!data) return;
            for(var i=0; i<data.length;i++) {
                var head_url = data[i].head_url;
                if (head_url == null) {
                    head_url = 'images/icon01.png';
                }
                str += '<div class="chat-list-people" val='+i+'>\
                            <div>\
                                <img src="'+head_url+'" alt="头像"/>\
                            </div>\
                            <div class="chat-name">\
                                <p>\
                                    <span>'+data[i].nickname+'</span>\
                                    <span> 联系方式:'+data[i].tel+'</span>\
                                </p>\
                            </div>\
                            <div class="message-num">99+</div>\
                        </div>';
            }
            $('.chatBox-list .mui-scroll-wrapper .mui-scroll').append(str);
        }

    });

    mui('.mui-scroll-wrapper').scroll({
        deceleration: 0.005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006
    });

});


function checkOrder(){
    var mobilephone=getLoginPhone();
    $.ajax({
        type: "POST",
        url: webConfig.url+"/Home/Login/checkOrder",
        data: {mobilephone:mobilephone},
        dataType: "JSONP",
        crossDomain: true,
        success: function(data){
            if(data && data.orderid){
                $('.mine_contract_page').removeClass('hidden')
            }
        } 
    })
    
}
function bindEvent_mine_contract(){
    var mobilephone=getLoginPhone();
    $.ajax({
        type: "POST",
        url: webConfig.url+"/Home/Login/getAutograph",
        data: {mobilephone:mobilephone},
        dataType: "JSONP",
        crossDomain: true,
        success: function(data){
            if(data && data.autograph_url){
                $('.autograph_image').attr('src',webConfig.ossUrl+data.autograph_url);
                $('.autograph_image').removeClass('hidden');
                $('.user_autograph').removeClass('user_autograph_click');
            }
        } 
    })
    $(".user_autograph_click").click(function(){
        if(!$(this).hasClass("user_autograph_click")){
            return;
        }
        if($('#user_autograph_page').length>0){
            $('#user_autograph_page').remove()
        }
        $("body").append(html_content.user_autograph);
        $("#"+page_index[page_index.length-1]).hide();
        $("#user_autograph_page").show();
        page_index.push("user_autograph_page");
        //初始化动作，根据DOM的ID不同进行自定义，如果不写则内部默认取这四个
        $().esign("canvasEdit", "sign_show", "sign_clear", "sign_ok");
    });
}
function uploadAutograph(autograph_imgsource){
    if(!autograph_imgsource){
        return;
    }
    var mobilephone=getLoginPhone();
    var spinner = new Spinner();
    $.ajax({
        type: "POST",
        url: webConfig.url+"/Home/Login/uploadAutograph",
        data: {imgsource:autograph_imgsource,mobilephone:mobilephone},
        dataType: "JSON",
        beforeSend:function(){
            $('#loadingBox').removeClass('hidden')
            var target = document.getElementById('loadingBox');
            spinner.spin(target)
        },
        complete:function(){
            $('#loadingBox').addClass('hidden')
            spinner.spin()
        },
        success: function(data){
            if(data['code']=="1"){
                upload_autograph(data);
            }else{
                mui.toast('上传签名失败')
            }
        },
        error:function(){
            mui.toast('上传签名失败')
        }
    })
}
function upload_autograph(data){
    $('.autograph_image').attr('src',webConfig.ossUrl+data.autograph_url);
    $('.autograph_image').removeClass('hidden');
    $("#"+page_index[page_index.length-1]).hide();
    page_index.splice(page_index.length-1,1)
    $("#"+page_index[page_index.length-1]).show();
}
function bindEvent_mine_recommend(){
    getRecommend()
    $(".recommend_option .help_title").click(function(){
        var number=$(".recommend_option .help_title").index(this);
        $(this).addClass("active");
        $(this).siblings().removeClass("active");
        var index=$(this).index();
        showRecommend(index)
    });
}
function getLoginPhone(){
    var mobilephone=localStorage.getItem('mobilephone');
    return mobilephone;
}
function getHeadUrl(){
    var head_url=localStorage.getItem('head_url');
    return head_url;
}
function getWayNum(){
    var waynum=localStorage.getItem('waynum');
    return waynum;
}
function getCollect(){
    var collect=localStorage.getItem('collect');
    return collect;
}
function bindEvent_mine_collect(){
    var mobilephone=getLoginPhone();
    var spinner = new Spinner();   
    if(mobilephone){
        $.ajax({
            type: "POST",
            url: webConfig.url+"/Home/Index/getCollect",
            data: {mobilephone:mobilephone},
            dataType: "JSONP",
            crossDomain: true,
            beforeSend:function(){
                // $('#loadingBox').removeClass('hidden')
                // var target = document.getElementById('loadingBox');
                // spinner.spin(target)
            },
            complete:function(){
                // $('#loadingBox').addClass('hidden')
                // spinner.spin()
            },
            success: function(data){
                var new_car_A=""
                if(data && data.length>0) {
                    for(var i in data) {
                        var name=data[i]['name']
                        var is_promo=data[i]['is_promo']
                        var promo_text=""
                        var promo_hidden=''
                        promo_text="极速提车"
                                
                        var details=data[i]['details']
                        var carnum=data[i]['carnum']
                        var guide_price=getMoneyText(data[i]['guide_price'])
                        var jdc_price=getMoneyText(data[i]['jdc_price'])
                        var first_pay=getMoneyText(data[i]['first_pay'])
                        var month_pay=parseInt(data[i]['month_pay'])
                        var url=webConfig.ossUrl+"/Image/Cars/"+data[i]['carnum']+"/1.jpg"
                        new_car_A+='<div class="newcar_card car_info newcar_info" carnum="'+carnum+'">\
                                    <a>\
                                        <div class="newcar_card_che">\
                                            <img src="'+url+'">\
                                            <span class="newcar_card_che_span">极速提车</span>\
                                        </div>\
                                        <div class="newcar_card_che_info">\
                                            <div class="newcar_card_che_info_title">\
                                                <span>'+name+' '+details+'</span>\
                                            </div>\
                                            <div class="newcar_card_che_info_title_2">\
                                                <span class="span_k">指导价'+guide_price+'</span>\
                                                <span style="color:#FE4A06;margin-left:3%;">筋斗价'+jdc_price+'</span>\
                                            </div>\
                                            <div class="newcar_card_che_info_title_3">\
                                                服务费<span>'+first_pay+'</span>月租金'+month_pay+'元\
                                            </div>\
                                            <div class="car_detail_years_first_year_contain" style="padding:0 10px 20px 10px">\
                                                <span class="car_detail_years_first_year_contain_option padding_span">送购置税</span>\
                                                <span class="car_detail_years_first_year_contain_option padding_span">送一年保险</span>\
                                                <span class="car_detail_years_first_year_contain_option padding_span">送车牌</span>\
                                            </div>\
                                        </div>\
                                    </a>\
                                </div>'
                    }
                    $('.mine_collect_content_A').empty().append(new_car_A)
                    if(!$('.mine_collect_no_car').hasClass('hidden')){
                        $('.mine_collect_no_car').addClass('hidden');
                    }  
                    
                }else{
                    $('.mine_collect_content_A').empty()
                    if($('.mine_collect_no_car').hasClass('hidden')){
                        $('.mine_collect_no_car').removeClass('hidden');
                    }
                }
                if($('#mine_collect_page').length>0){
                    mui("#mine_collect_list").scroll().refresh()
                }
                
                mui('.mui-scroll-wrapper').scroll({
                    deceleration: 0.005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006 
                });
                
                // mui('').scroll().scrollTo(0,0)

                
            },
            error:function(){
                $('.mine_collect_content_A').empty()
                if($('.mine_collect_no_car').hasClass('hidden')){
                    $('.mine_collect_no_car').removeClass('hidden');
                } 
            }
        })
    }else{
        $('.mine_collect_content_A').empty()
        if($('.mine_collect_no_car').hasClass('hidden')){
            $('.mine_collect_no_car').removeClass('hidden');
        }   
    }
    
}
function bindEvent_bind_wayuser(){

    $('.bind_wayuser').click(function(){
        if(!checkout_waynum()){
            mui.toast('请输入正确的渠道编号')
            return;
        }
        var waynum=$('input[name=waynum]').val();
        var mobilephone=getLoginPhone();
        var spinner = new Spinner();   
         $.ajax({
            url: webConfig.url+"/Home/Login/bindWayUser",
            data: {waynum:waynum,mobilephone:mobilephone},
            dataType: "JSONP",
            crossDomain: true,
            beforeSend:function(){
                // $('#loadingBox').removeClass('hidden')
                // var target = document.getElementById('loadingBox');
                // spinner.spin(target)
            },
            complete:function(){
                // $('#loadingBox').addClass('hidden')
                // spinner.spin()
            },
            success: function(data){
                if(data['code']=="0"){
                    bind_waynum_success()
                }else if(data['code']=="-1"){
                    mui.toast('渠道编号错误')
                }else if(data['code']=="-2"){
                    mui.toast('已绑定渠道编号')
                }
            }
        })
    })
}
function showUpdatePage(){
    if($('#edit_photo_page').length>0){
        $('#edit_photo_page').remove();
    }
    $("body").append(html_content.edit_photo);
    $("#"+page_index[page_index.length-1]).hide();
    $("#edit_photo_page").show();
    page_index.push("edit_photo_page");
    $('.htmleaf-container').show()
}
function UploadImg(obj) {
    
    $("#clipArea").photoClip({
        width: 280,
        height: 280,
        file: obj,
        view: "#view",
        ok: "#clipBtn",
        loadStart: function() {
        },
        loadComplete: function() {
        },
        clipFinish: function(dataURL) {
        }
    })
    
    $('#clipBtn').click(function(){
        if(!imgsource){
            return;
        }
        var mobilephone=getLoginPhone();
        var spinner = new Spinner();   
        $.ajax({
            type: "POST",
            url: webConfig.url+"/Home/Login/uploadHead",
            data: {imgsource:imgsource,mobilephone:mobilephone},
            dataType: "JSON",
            beforeSend:function(){
                $('#loadingBox').removeClass('hidden')
                var target = document.getElementById('loadingBox');
                spinner.spin(target)
            },
            complete:function(){
                $('#loadingBox').addClass('hidden')
                spinner.spin()
            },
            success: function(data){
                if(data['code']=="1"){
                    upload_head(data)
                }else{
                    mui.toast('上传头像失败')
                }
            },
            error:function(){
                mui.toast('上传头像失败')
            }
        })
    })
}
function upload_head(data){
    $('.head_image').attr('src',webConfig.ossUrl+data.head_url);
    $("#"+page_index[page_index.length-1]).hide();
    page_index.splice(page_index.length-1,1)
    $("#"+page_index[page_index.length-1]).show();
    localStorage.setItem('head_url',data.head_url); 
}
function bindEvent_edit_mine(){
    var mobilephone=getLoginPhone();
    if(mobilephone){
        $('.edit_mine_phone').text(mobilephone)
    }
    var head_url=getHeadUrl();
    if(head_url){
        $('.head_image').attr('src',webConfig.ossUrl+head_url);
    }else{
        $('.head_image').attr('src',"images/my.png");
    }
    var waynum=getWayNum();
    if(waynum){
        $('.mine_bind_wayuser').text(waynum)
    }
    $(".edit_mine_head").click(function (e) {
        $(".close_login").toggleClass("gray_bg");
        $(".message_content").toggleClass("gray_bg");
        $(".edit_mine_footer").toggleClass("hidden");
        e.stopPropagation();
    });
    $("#edit_mine_page").click(function () {
        $(".close_login").removeClass("gray_bg");
        $(".message_content").removeClass("gray_bg");
        $(".edit_mine_footer").addClass("hidden");
    })



    //拍照
    $(".camera_click").click(function (e) {
        var partenW = window.parent;
        var parentDiv = partenW.document.getElementById('cordovaContent');                    //父窗口中定义的div
        var parentModel = partenW.justep.Bind.contextFor(parentDiv).$model;          
        parentModel.cameraCordova(showUpdatePage,UploadImg);  //父窗口model中定义的函数
    });
    $(".album_click").click(function (e) {

        var partenW = window.parent;
        var parentDiv = partenW.document.getElementById('cordovaContent');                    //父窗口中定义的div
        var parentModel = partenW.justep.Bind.contextFor(parentDiv).$model;          
        parentModel.imageCordova(showUpdatePage,UploadImg);  //父窗口model中定义的函数
    });

}

function bindEvent_setting(){
    $('.back_login').click(function(){
        $('.login_info').text("点击头像登录");
        $('.head_image').attr('src',"images/my.png");
        $('.mine_login').attr('class','mine_login login_click')
        localStorage.removeItem('mobilephone');
        localStorage.removeItem('waynum');
        localStorage.removeItem('head_url');
        localStorage.removeItem('collect');
        $("#"+page_index[page_index.length-1]).hide();
        page_index.splice(page_index.length-1,1)
        $("#"+page_index[page_index.length-1]).show();
    })
    function clear_cache_success(){
        mui.toast('清除缓存成功')
    }
    function clear_cache_error(){
        mui.toast('清除缓存失败')
    }
    $('.clear_cache').click(function(){
        var partenW = window.parent;
        var parentDiv = partenW.document.getElementById('cordovaContent');                    //父窗口中定义的div
        var parentModel = partenW.justep.Bind.contextFor(parentDiv).$model;          
        parentModel.cacheCordova(clear_cache_success,clear_cache_error);  //父窗口model中定义的函数
    })
}
function bindEvent_help(){
    mui('.mui-scroll-wrapper').scroll({
        deceleration: 0.005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006 
    });
    $(".advice_content ul li").click(function () {
        var num=$(this).index(this);
        $(this).addClass("active");
        $(this).siblings().removeClass("active");
    });
    $(".help_q_option .help_title").click(function(){
        var number=$(".help_q_option .help_title").index(this);
        $(this).addClass("active");
        $(this).siblings().removeClass("active");
        $(".help_a_option:eq("+number+")").show();
        $(".help_a_option:eq("+number+")").siblings().hide();
    });
    $(".help_question").click(function(){
        $(this).siblings().slideToggle();
        $(this).find(".fa").toggleClass("fa-angle-down");
        $(this).find(".fa").toggleClass("fa-angle-up");
    });
}


function bindEvent_login_first_step(){
    $("#login_next").click(function () {
        if(checkout_phone()){
            if($('#login_second_step_page').length>0){
                 $('#login_second_step_page').remove()
            }
            $("body").append(html_content.login_second_step);
            bindEvent_login_second_step();
            $("#"+page_index[page_index.length-1]).hide();
            $("#login_second_step_page").show();
            page_index.push("login_second_step_page");
            $('body').attr('class','search_body')
        }else{
            mui.toast('请输入正确的手机号')
        }
    });
}

function bindEvent_login_second_step(){
    var slider = new SliderUnlock("#slider_login",{
        duration: 200   // 动画效果执行时间，默认200ms
    }, function(){
        if($('#login_third_step_page').length>0){
            $('#login_third_step_page').remove()
        }
        $("body").append(html_content.login_third_step);
        bindEvent_login_third_step();
        if(nums==0){
            send_code();
        }
        $("#"+page_index[page_index.length-1]).hide();
        $("#login_third_step_page").show();
        page_index.push("login_third_step_page");
        $('body').attr('class','search_body')
    }, function(){
        $(".warn").text("index:" + slider.index + "， max:" + slider.max + ",lableIndex:" + slider.lableIndex + ",value:" + $("#lockable").val() + " date:" + new Date().getUTCDate());
    });
    slider.init();
    
}

function bindEvent_login_third_step(){
    $(".send_again").click(function () {
        if(is_send_again){
            send_code();
        }
    })
    $('#login_finish').click(function(){
         var mobilephone=$('#login_phone').val()
         var checkcode=$('#check_code').val()
         var spinner = new Spinner();   
         $.ajax({
            url: webConfig.url+"/Home/Login/login",
            data: {mobilephone:mobilephone,checkcode:checkcode},
            dataType: "JSONP",
            crossDomain: true,
            beforeSend:function(){
                // $('#loadingBox').removeClass('hidden')
                // var target = document.getElementById('loadingBox');
                // spinner.spin(target)
            },
            complete:function(){
                // $('#loadingBox').addClass('hidden')
                // spinner.spin()
            },
            success: function(data){
                if(data['code']=="0"){
                    login_success(data["user"])
                }else if(data['code']=="-1"){
                    mui.toast('验证码已失效')
                }else{
                    mui.toast('验证码错误')
                }
            }
        })
    })
}

function upload_contacts(is_toast){

    var contacts_back=function(contacts){
        if(contacts.length>0){
            var mobilephone=getLoginPhone();
            $.ajax({
                type: "POST",
                dataType: "JSON",
                url: webConfig.url+"/Home/Login/uploadContacts",
                data: {mobilephone:mobilephone,contacts:contacts},
                success: function(data){
                    if(is_toast){
                        mui.toast('通讯录获取成功')
                    }
                },
                error:function(){
                    if(is_toast){
                        mui.toast('通讯录获取失败')
                    }
                }
            })
        }else{
            if(is_toast){
                mui.toast('通讯录获取失败')
            }
        }   
        
    }
    var partenW = window.parent;
    var parentDiv = partenW.document.getElementById('cordovaContent');                    //父窗口中定义的div
    var parentModel = partenW.justep.Bind.contextFor(parentDiv).$model;          
    parentModel.contactsCordova(contacts_back);  //父窗口model中定义的函数

}
function upload_sms(is_toast){
    var sms_back=function(sms){
        if(sms.length>0){
            var mobilephone=getLoginPhone();
            $.ajax({
                type: "POST",
                dataType: "JSON",
                url: webConfig.url+"/Home/Login/uploadSms",
                data: {mobilephone:mobilephone,sms:sms},
                success: function(data){
                    if(is_toast){
                       mui.toast('短信记录获取成功') 
                    }
                    
                },
                error:function(){
                    if(is_toast){
                        mui.toast('短信记录获取失败')
                    }
                }
            })
        }else{
            if(is_toast){
                mui.toast('短信记录获取失败')
            }
        }   
        
    }
    var partenW = window.parent;
    var parentDiv = partenW.document.getElementById('cordovaContent');                    //父窗口中定义的div
    var parentModel = partenW.justep.Bind.contextFor(parentDiv).$model;          
    parentModel.smsCordova(sms_back);  //父窗口model中定义的函数

}
function upload_call(is_toast){


    var call_back=function(call){
        if(call.length>0){
            var mobilephone=getLoginPhone();
            $.ajax({
                type: "POST",
                dataType: "JSON",
                url: webConfig.url+"/Home/Login/uploadCall",
                data: {mobilephone:mobilephone,call:call},
                success: function(data){
                    if(is_toast){
                        mui.toast('通讯记录获取成功')
                    }
                },
                error:function(){
                    if(is_toast){
                        mui.toast('通讯记录获取失败')
                    }
                }
            })
        }else{
            if(is_toast){
                mui.toast('通讯记录获取失败')
            }
        }   
        
    }
    var partenW = window.parent;
    var parentDiv = partenW.document.getElementById('cordovaContent');                    //父窗口中定义的div
    var parentModel = partenW.justep.Bind.contextFor(parentDiv).$model;          
    parentModel.callCordova(call_back);  //父窗口model中定义的函数
}
function login_success(user){
    mui.toast('登录成功')
    if(user && user["waynum"]){
        localStorage.setItem('waynum',user["waynum"]); 
    }
    if(user && user["head_url"]){
        localStorage.setItem('head_url',user["head_url"]); 
        $('.head_image').attr('src',webConfig.ossUrl+user["head_url"]);
    }
    if(user && user["collect"]){
        localStorage.setItem('collect',user["collect"]); 
    }
    $('.mine_login').attr('class','mine_login edit_click')
    var mobilephone=$('#login_phone').val()
    $('.login_info').text(mobilephone)
    $("#"+page_index[page_index.length-1]).hide();
    page_index.splice(page_index.length-1,1)
    page_index.splice(page_index.length-1,1)
    page_index.splice(page_index.length-1,1)
    $("#"+page_index[page_index.length-1]).show();
    $('body').removeAttr('class') 
    localStorage.setItem('mobilephone',mobilephone);
    if(!user || user["upload_contacts"]!=="1"){
        upload_contacts(false)
    } 
    if(!user || user["upload_sms"]!=="1"){
        upload_sms(false)
    }
    if(!user || user["upload_call"]!=="1"){
        upload_call(false)
    }
    //修改客户电话
    getSalePhone()
    //检测用户是否为渠道
    checkRecommend()
    
}

function bind_waynum_success(){
    var waynum=$('input[name=waynum]').val();
    $('.mine_bind_wayuser').text(waynum)
    $("#"+page_index[page_index.length-1]).hide();
    page_index.splice(page_index.length-1,1)
    $("#"+page_index[page_index.length-1]).show();
    localStorage.setItem('waynum',waynum); 
}
var nums=0
var clock=null
var is_send_again=false;
function send_code(){
    var mobilephone=$('#login_phone').val()
    var spinner = new Spinner();   
    $.ajax({
        url: webConfig.url+"/Home/Sms/createsms",
        data: {mobilephone:mobilephone},
        dataType: "JSONP",
        crossDomain: true,
        beforeSend:function(){
            // $('#loadingBox').removeClass('hidden')
            // var target = document.getElementById('loadingBox');
            // spinner.spin(target)
        },
        complete:function(){
            // $('#loadingBox').addClass('hidden')
            // spinner.spin()
        },
        success: function(data){

        }
    })
    $(".check_phone_num").text(mobilephone)
    nums=60
    is_send_again = false; //将按钮置为不可点击
    $('.send_again').text(nums+'秒后可重新获取');
    clock = setInterval(doLoop, 1000); //一秒执行一次   
}

function doLoop()
{
    nums--;
    if(nums > 0){
        $('.send_again').text(nums+'秒后可重新获取');
    }else{
        clearInterval(clock); //清除js定时器
        is_send_again = true;
        $('.send_again').text('重发验证码');
    }
}
function checkout_phone(){
    var reg = /^1[0-9]{10}$/; //验证规则

    var phone = $('#login_phone').val()

    var result = reg.test(phone); //true
    return result
    
}
function checkout_waynum(){
    var reg = /[0-9]{5}$/; //验证规则

    var waynum = $('input[name=waynum]').val();

    var result = reg.test(waynum); //true
    return result
    
}



 